package com.efast.cafe.portal.service.company.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.jdbc.JdbcDao;
import com.efast.cafe.framework.jdbc.JdbcDaoImpl;
import com.efast.cafe.framework.jdbc.persistence.Criteria;
import com.efast.cafe.portal.dao.company.PortalCompanyRegisterDao;
import com.efast.cafe.portal.entity.base.BaseCompanyInfo;
import com.efast.cafe.portal.entity.common.ModuleCompany;
import com.efast.cafe.portal.entity.common.ModuleInfo;
import com.efast.cafe.portal.entity.company.PortalCompanyRegister;
import com.efast.cafe.portal.entity.company.PortalCompanyRole;
import com.efast.cafe.portal.entity.company.PortalCompanyUser;
import com.efast.cafe.portal.entity.company.PortalCompanyUserRole;
import com.efast.cafe.portal.remote.company.PortalCompanyRegisterActivateCodeService;
import com.efast.cafe.portal.service.company.IPortalCompanyRegisterActivateCodeService;
import com.efast.cafe.portal.service.company.IPortalCompanyRegisterService;
import com.efast.cafe.util.ConfigUtil;
import com.efast.cafe.util.PinyinAPI;

/******************************************************************************
 * @File name : PortalCompanyRegisterServiceImpl.java
 * 
 * @Author : xl
 * 
 * @Date : 2016-6-23
 * 
 * @Copyright Notice: Copyright (c) 2016 Efast Serv. All Rights Reserved. This
 *            software is published under the terms of the Efast Software
 *            License version 1.0, a copy of which has been included with this
 *            distribution in the LICENSE.txt file.
 * 
 * 
 *            ------------------------------------------------------------------
 *            ---------- Date Who Version Comments 2016-6-23 上午8:57:11 xl 1.0
 *            Initial Version
 *****************************************************************************/

@Service
@Transactional
public class PortalCompanyRegisterServiceImpl implements
		IPortalCompanyRegisterService {
	
	@Qualifier("jdbcDao")
	@Autowired
	private  JdbcDao  jdbcDao;
	
	
	@Autowired
	private PortalCompanyRegisterDao portalCompanyRegisterDao;


	private IPortalCompanyRegisterActivateCodeService portalCompanyRegisterActivateCodeService;

	

	@Autowired
	public void setPortalCompanyRegisterActivateCodeService(
			IPortalCompanyRegisterActivateCodeService portalCompanyRegisterActivateCodeService) {
		this.portalCompanyRegisterActivateCodeService = portalCompanyRegisterActivateCodeService;
	}

	/**
	 * {@inheritDoc} overridden:
	 * 
	 * @Date : 2016-6-23
	 * @see org.eae.eldf.portal.remote.company.PortalCompanyRegisterService#register(org.eae.eldf.portal.po.company.PortalCompanyRegister)
	 **/
	@Override
	public void register(PortalCompanyRegister register) {
		Criteria criteria = Criteria.create(PortalCompanyRegister.class).where(
				"email", new Object[] { register.getEmail() });
		List<PortalCompanyRegister> list = jdbcDao
				.queryList(criteria);
		// 判断邮箱是否存在
		if (list.size() > 0) {
			PortalCompanyRegister portalCompanyRegister = list.get(0);
			// 判断邮箱是否激活
			if (0 == portalCompanyRegister.getActivated()) {
				// 判断激活时间是否过期
				if (portalCompanyRegister.getActivate_valid_time().after(
						new Date())) { // 未过期 未激活的情况
					// 该邮箱已被注册，尚未激活，请激活该邮箱
					throw new ServiceException(
							"msg.portal.company.register.email.no.register");
				} else {// 未激活 已过期的情况
					try {
						// 重新生成激活码
						String activate_code = UUID.randomUUID().toString();
						// 修改数据 重新生成激活码 和 激活截止时间
						portalCompanyRegisterActivateCodeService
								.updateCompanyRegisterActivateCode(
										activate_code,
										getNextDay(new Date()),
										portalCompanyRegister
												.getPortal_company_register_id());
						// 重新发送激活邮件
						sendActivatEmail(register.getEmail(), activate_code);
					} catch (AddressException e) {
						// 邮箱地址错误
						throw new ServiceException(
								"msg.portal.company.register.email.format");
					} catch (MessagingException e) {
						// 网络异常
						throw new ServiceException(
								"msg.portal.company.register.network.problem");
					}
					// 该邮箱已被注册，尚未激活，已重新发送激活邮件，请激活该邮箱
					throw new ServiceException(
							"msg.portal.company.register.email.again.register");
				}
			} else {
				// 邮箱已被注册
				throw new ServiceException(
						"msg.portal.company.register.email.already.exist");
			}

		} else {
			String activate_code = UUID.randomUUID().toString();
			// 发送激活邮件
			try {
				sendActivatEmail(register.getEmail(), activate_code);
			} catch (AddressException e) {
				// 邮箱地址错误
				throw new ServiceException(
						"msg.portal.company.register.email.format");
			} catch (MessagingException e) {
				// 网络异常
				throw new ServiceException(
						"msg.portal.company.register.network.problem");
			}
			Criteria criteriaRegister = Criteria
					.create(PortalCompanyRegister.class)
					.set("company_domain", register.getCompany_domain())
					.set("real_name", register.getReal_name())
					.set("company_name", register.getCompany_name())
					.set("mobile", register.getMobile())
					.set("email", register.getEmail())
					.set("pwd", register.getPwd()).set("activated", 0)
					.set("activate_valid_time", getNextDay(new Date()))
					.set("register_time", new Date())
					.set("activate_code", activate_code);
			jdbcDao.insert(criteriaRegister);

		}
	}

	/**
	 * {@inheritDoc} overridden:
	 * 
	 * @Date : 2016-6-23
	 * @see org.eae.eldf.portal.remote.company.PortalCompanyRegisterService#registerActivate(java.lang.String,
	 *      java.lang.String)
	 **/
	@Override
	public void registerActivate(String activate_code) throws ServiceException {
		Criteria criteria = Criteria.create(PortalCompanyRegister.class).where(
				"activate_code", new Object[] { activate_code });
		List<PortalCompanyRegister> list = jdbcDao
				.queryList(criteria);
		// 判断邮箱是否存在
		if (list.size() > 0) {
			PortalCompanyRegister portalCompanyRegister = list.get(0);
			// 判断该邮箱是否激活
			if (portalCompanyRegister.getActivated() == 1) {
				// 该邮箱已激活
				throw new ServiceException(
						"msg.portal.company.register.email.register");
			} else {

				// 判断是否在激活截止日期内
				if (portalCompanyRegister.getActivate_valid_time().after(
						new Date())) { //邮箱未激活 在有效期内的情况
					// 生成企业信息 portal_company_info
					String companyCode = PinyinAPI
							.getPinYinHeadChar(portalCompanyRegister
									.getCompany_name());
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(new Date());
					calendar.add(Calendar.DAY_OF_YEAR, +1);
					Criteria companyInfo = Criteria
							.create(BaseCompanyInfo.class)
							.set("companyName",
									portalCompanyRegister.getCompany_name())
							.set("isEnable", 1)
							.set("validStart", new Date())
							// 有效期开始从当前时间开始
							.set("validEnd", calendar.getTime())
							// 有效期结束为1年
							.set("companyDomain",
									portalCompanyRegister.getCompany_domain())
							.set("companyCode", companyCode);
					jdbcDao.insert(companyInfo);

					// 生成企业管理员账号 portal_company_user
					Criteria companyUser = Criteria
							.create(PortalCompanyUser.class)
							.set("username", portalCompanyRegister.getEmail())
							.set("email", portalCompanyRegister.getEmail())
							.set("archived", 0)
							.set("lastUpdateTime", new Date())
							.set("companyCode", companyCode)
							.set("pwd", new BCryptPasswordEncoder().encode(portalCompanyRegister.getPwd()))
							.set("defaultUser", 1)//默认管理员账号
							.set("phone", portalCompanyRegister.getMobile());
					jdbcDao.insert(companyUser);

					// 给企业分配默认模块
					List<ModuleInfo> listModuleInfo = portalCompanyRegisterDao
							.queryDefaultModuleInfo();
					Object[] moduleInfoId = new Object[listModuleInfo.size()];
					for (int i = 0; i < listModuleInfo.size(); i++) {
						if(listModuleInfo.get(i)!=null){
							moduleInfoId[i] = listModuleInfo.get(i)
									.getModuleInfoId();
							Criteria criteriaModuleCompany = Criteria
									.create(ModuleCompany.class)
									.set("moduleInfoId", moduleInfoId[i])
									.set("companyCode", companyCode);
							jdbcDao.insert(criteriaModuleCompany);
						}
						
					}

					// 给企业管理员设置默认角色
					Criteria criteriaPortalCompanyRole = Criteria
							.create(PortalCompanyRole.class)
							.where("companyCode", new Object[] { "system" })
							.and("moduleInfoId", moduleInfoId)
							.and("isDefaultRole", new Object[] { 1 });
					List<PortalCompanyRole> listPortalCompanyRole = jdbcDao
							.queryList(criteriaPortalCompanyRole);
					for (PortalCompanyRole portalCompanyRole : listPortalCompanyRole) {
						Criteria criteriaPortalCompanyUserRole = Criteria
								.create(PortalCompanyUserRole.class)
								.set("companyCode", companyCode)
								.set("username",
										portalCompanyRegister.getEmail())
								.set("portalCompanyRoleId",
										portalCompanyRole
												.getPortalCompanyRoleId());
						jdbcDao
								.insert(criteriaPortalCompanyUserRole);
					}

					// 修改企业注册信息状态
					jdbcDao
							.update(Criteria
									.create(PortalCompanyRegister.class)
									.set("activated", 1)
									.where("portal_company_register_id",
											new Object[] { portalCompanyRegister
													.getPortal_company_register_id() }));

					
				} else {//邮箱未激活 激活码已过期的情况
					try {
						//重新生成激活码
						activate_code = UUID.randomUUID().toString();
						// 修改数据 重新生成激活码 和 激活截止时间
						portalCompanyRegisterActivateCodeService
								.updateCompanyRegisterActivateCode(
										activate_code,
										getNextDay(new Date()),
										portalCompanyRegister
												.getPortal_company_register_id());
						// 重新发送邮件
						sendActivatEmail(portalCompanyRegister.getEmail(),
								activate_code);
					} catch (AddressException e) {
						// 邮箱地址错误
						throw new ServiceException(
								"msg.portal.company.register.email.format");
					} catch (MessagingException e) {
						// 网络异常
						throw new ServiceException(
								"msg.portal.company.register.network.problem");
					}
					// 该激活码已过期
					throw new ServiceException(
							"msg.portal.company.register.email.expired");
				}
			}

		} else {
			// 无效激活码
			throw new ServiceException(
					"msg.portal.company.register.email.no.valid");
		}

	}

	/**
	 * 
	 * @Date : 2016-6-23
	 * @param email
	 * @throws MessagingException
	 * @throws AddressException
	 */
	// 发送邮件
	public static void sendActivatEmail(String email, String activate_code)
			throws AddressException, MessagingException {
//		SimpleMailSender sms = MailSenderFactory.getSender(
//				ConfigUtil.getValue("cafe.mail.smtp.host"),
//				ConfigUtil.getValue("cafe.mail.fromEmail"),
//				ConfigUtil.getValue("cafe.mail.fromPwd"));
//		sms.send(email, "邮箱激活",
//				ConfigUtil.getValue("cafe.mail.activate.baseurl")
//						+ "?activate_code=" + activate_code);

	}

	public static Date getNextDay(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, +1);// +1今天的时间加一天
		date = calendar.getTime();
		return date;
	}
}
